﻿using Microsoft.AspNetCore.Mvc.Filters;
using System;
using Microsoft.Extensions.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using StackExchange.Profiling;
using System.Net;
using Filters.Models;

namespace easyui.Filter
{
    public class GlobalExceptionFilter : IExceptionFilter
    {
        //private readonly IHostingEnvironment _env;//已过时 
        private readonly IWebHostEnvironment _env;
        public GlobalExceptionFilter(IWebHostEnvironment env)
        {
            _env = env;
        }
        public void OnException(ExceptionContext context)
        {
            var json = new JsonErrorResponse();
            json.Message = context.Exception.Message;//错误信息
            var errorAudit = "Unable to resolve service for";
            if (!string.IsNullOrEmpty(json.Message) && json.Message.Contains(errorAudit))
            {
                json.Message = json.Message.Replace(errorAudit, $"（若新添加服务，需要重新编译项目）{errorAudit}");
            }

            if (_env.IsDevelopment())
            {
                json.DevelopmentMessage = context.Exception.StackTrace;//堆栈信息
            }

            HttpStatusCode status = HttpStatusCode.InternalServerError;

            //处理各种异常
            context.ExceptionHandled = true;
            context.Result = new CustomExceptionResult((int)status, context.Exception);


            MiniProfiler.Current.CustomTiming("Errors:",json.Message);
            #region 输出到当前项目日志
            var logPath = Directory.GetCurrentDirectory() + "/Log";
            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }
            string filename = logPath + $"/ExceptLog-{DateTime.Now.ToString("yyyyMMdd")}.log";
            StreamWriter sw = File.AppendText(filename);
            sw.WriteLine(json.Time + Environment.NewLine +json.Message);
            sw.Close();
            #endregion
        }
    }

    public class InternalServerErrorObjectResult : ObjectResult
    {
        public InternalServerErrorObjectResult(object value) : base(value)
        {
            StatusCode = StatusCodes.Status500InternalServerError;
        }
    }

    public class JsonErrorResponse
    {
        public string Time { get { return DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"); } }
        /// <summary>
        /// 生产环境的消息
        /// </summary>
        public string Message { get; set; }

        /// <summary>
        /// 开发环境信息
        /// </summary>
        public string DevelopmentMessage { get; set; }
    }
}
